package com.lucifer.cloud.boot.blog.nl2sql.api;

import com.lucifer.cloud.boot.blog.nl2sql.builder.TrainBuilder;
import com.lucifer.cloud.boot.blog.nl2sql.domain.req.ChatReq;
import com.lucifer.cloud.boot.blog.nl2sql.engine.RagEngine;
import com.lucifer.cloud.boot.blog.nl2sql.engine.SpringSqlEngine;
import com.lucifer.cloud.boot.blog.nl2sql.enumd.TrainPolicyType;
import com.lucifer.cloud.boot.blog.nl2sql.vector.BaseVectorStore;
import jakarta.annotation.Resource;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

/**
 * @author lucifer
 * @date 2025/3/19 10:55
 */
@Service
public class Nl2SqlApi {


    @Resource
    private BaseVectorStore vectorStore;

    @Resource
    private RagEngine ragEngine;


    @Resource
    private ZhiPuAiChatModel chatModel;


    @Resource
    private ResourceLoader resourceLoader;


    @Resource
    private SpringSqlEngine sqlEngine;


    public void train(
          String  conversationId,
          String  question,
          String  content,
          String  policy,
          String  tableName
    ){
        TrainBuilder builder = TrainBuilder.builder()
                .conversationId(conversationId)
                .question(question)
                .content(content)
                .policy(TrainPolicyType.valueOf(policy))
                .tableName(tableName).build();
        sqlEngine = sqlEngine.builder(vectorStore, ragEngine, chatModel, resourceLoader);
        sqlEngine.train(builder);
    }


    public String nl2sql(
      String  conversationId,
      String  question,
      String  policy,
      String  tableName
    ){
        sqlEngine = sqlEngine.builder(vectorStore, ragEngine, chatModel, resourceLoader);
        ChatReq chatReq = ChatReq.builder().question(question).tableName(tableName).build();
        String sql = sqlEngine.setChatModel(chatModel).generateSql(chatReq);
        Object object;
        try {
            object = sqlEngine.executeSql(sql);
        } catch (Exception e) {
            object = "sql 执行错误："+ e.getMessage();
        }
        String text = sqlEngine.generateSummaryV2(conversationId,chatReq.getQuestion(),sql, object.toString());
        String format = sqlEngine.outStand(question, sql, text);
        return format;
    }
}
